import os
import base64
import datetime

class xml_history(object):
    def __init__(self):
        self.xml_save_path=os.path.join(os.path.dirname(os.path.dirname(__file__)),'history')
        self.keep_file_count=10   #保留历史记录多少条


    def create_xml_file(self,xml_data):
        '''
        创建一份xml文件
        :param xml_data: xml的数据
        :return:
        '''
        if isinstance(xml_data,str)==False or xml_data=='':
            return False

        if os.path.isdir(self.xml_save_path)==False:
            os.makedirs(self.xml_save_path)
        byte_data=bytes(xml_data, encoding='utf-8')
        encode_xml=base64.b64encode(byte_data)
        otime=datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
        with open(os.path.join(self.xml_save_path,otime),'wb') as f:
            f.write(encode_xml)
        self.__check_keep_file()
        return True

    def __check_keep_file(self):
        '''
        检测文件的数量，删除以往多余的数据
        :return:
        '''
        file_list=[]
        for (root, dirs, files) in os.walk(self.xml_save_path):
            file_list+=files
        filename_list=[]
        for sub_file in file_list:
            try:
                otime=datetime.datetime.strptime(sub_file,'%Y%m%d%H%M%S%f')
                filename_list.append(otime)
            except Exception as e:
                pass
        if filename_list.__len__() > self.keep_file_count:
            if filename_list.__len__()>1:
                filename_list.sort(reverse=True)

            remove_filename_list=filename_list[self.keep_file_count:]
            for remove_file in remove_filename_list:
                filename=remove_file.strftime('%Y%m%d%H%M%S%f')
                file_path=os.path.join(self.xml_save_path,filename)
                os.remove(file_path)
        return True

    def get_all_xml(self):
        '''
        获取xml的所有文件名字
        :return:
        '''
        file_list = []
        for (root, dirs, files) in os.walk(self.xml_save_path):
            file_list += files
        return file_list


    def get_xml_file(self,file_name=None):
        '''
        根据xml文件名获取文件内容
        :param file_name: xml文件名字
        :return:
        '''
        result={'code':1,'xml_data':'','msg':''}
        if isinstance(file_name,str)==False:
            result['msg']='参数错误'
            return result
        if os.path.isfile(os.path.join(self.xml_save_path,file_name))==False:
            result['msg']='历史记录不存在'
            return result
        with open(os.path.join(self.xml_save_path,file_name),'r') as f:
            data=f.read()
            data=base64.b64decode(data)
            data=data.decode('utf-8')
            result['xml_data']=data
            result['code']=0
        return result

    def delete_xml_history(self,file_name=None):
        """
        删除记录文件
        :param file_name: 文件名字
        :return:
        """
        result = {'code': 1, 'msg': ''}
        if isinstance(file_name, str) == False:
            result['msg'] = '参数错误'
            return result
        if os.path.isfile(os.path.join(self.xml_save_path,file_name))==False:
            result['msg']='历史记录不存在'
            return result
        os.remove(os.path.join(self.xml_save_path,file_name))
        result['code']=0
        return result


if __name__ == '__main__':
    xml_data = '<xml xmlns="http://www.w3.org/1999/xhtml"><variables></variables><block type="control_repeat" id="$Gi3t?#u9Chb=`kZgw3F" x="350" y="50"><value name="TIMES"><shadow type="math_whole_number" id="[N]w`[x3~/*TcJvJ8p:["><field name="NUM">10</field></shadow></value></block></xml>'
    xml_obj=xml_history()
    xml_obj.create_xml_file(xml_data)




